package com.cao.meet;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class AsyncTaskActivity extends AppCompatActivity {

    private ImageView async_image;
    private ProgressBar async_progress;
    private String imageUrl = "https://img.izhufu.net/uploads/userup/150514/bd_14315688927760.jpg";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_async_task);

        async_image = (ImageView) findViewById(R.id.async_image);
        async_progress = (ProgressBar) findViewById(R.id.async_progress);

        new MyAsyncTask().execute(imageUrl);

    }

    class MyAsyncTask extends AsyncTask<String,Void,Bitmap>{

        //onPreExecute用于异步处理前的操作
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //此处将progressBar设置为可见.
            async_progress.setVisibility(View.VISIBLE);
        }

        @Override
        protected Bitmap doInBackground(String... strings) {
            String url = strings[0];
            Bitmap bitmap = null;
            URLConnection connection;
            InputStream is;
            try {
                connection = new URL(url).openConnection();
                is = connection.getInputStream();
                //为了能更清楚的看清加载图片的等待过程，此处进行阻塞
                Thread.sleep(2000);
                BufferedInputStream bis = new BufferedInputStream(is);
                //通过decodeStream方法解析输入流
                bitmap = BitmapFactory.decodeStream(bis);
                is.close();
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            //对progressBar进行隐藏
            async_progress.setVisibility(View.GONE);
            //更新imageView显示获取到的bitmap对象
            async_image.setImageBitmap(bitmap);
        }
    }

}
